<script setup lang='ts' name="policy-message-add">
import type { FormInstance } from 'element-plus'

import { policyUpdate } from '@fl/api/fangjiaohui'
import UpdatedOss from '@fl/components/upLoad-oss.vue'
import { Editor } from '@fl/origin-components/Editor/index'
import { ElButton, ElDialog, ElForm, ElFormItem, ElInput, ElMessage } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { nextTick, reactive, ref, toRefs, watch } from 'vue'

const props = withDefaults(defineProps<{
    area: any
    data?: any
    modelValue: boolean
    videoType: any
}>(), {
    data: () => { },
})

const emits = defineEmits(['update:modelValue', 'confirm'])
const { area, data, modelValue, videoType } = toRefs(props)

const initialState = { catId: '', img: '', info: '', name: '', region: [], sortOrder: 0 }
const state = ref<any>(cloneDeep(initialState))

const title = ref('新增')
const formRef = ref()

const rules = reactive<any>({
    catId: [
        { message: '请选择', required: true, trigger: 'blur' },
    ],
    img: [
        { message: '请上传', required: true, trigger: 'blur' },
    ],
    info: [
        { message: '请输入', required: true, trigger: 'blur' },
    ],
    name: [
        { message: '请输入', required: true, trigger: 'blur' },
    ],
})

async function doSave(formEl: FormInstance | undefined) {
    if (!formEl)
        return
    await formEl.validate((valid, fields) => {
        if (valid) {
            const {
                catId,
                id,
                img,
                info,
                name,
                region: regionMap,
                sortOrder,
            } = state.value

            const catName = videoType.value.find((v: any) => v.id === catId)?.name
            const region = regionMap.length ? regionMap.join(',') : ''

            policyUpdate({
                catId,
                catName,
                id,
                img,
                info,
                name,
                region,
                sortOrder,
            }).then((res: any) => {
                if (res.code === 200) {
                    close(formEl)
                    emits('confirm')
                }
                else {
                    ElMessage({ message: res.msg, type: 'error' })
                }
            }).catch((err) => {
                const message = err?.response?.data?.message || err
                ElMessage({ message, type: 'error' })
            })
        }
        else { console.log('error submit!', fields) }
    })
}

function close(formEl: FormInstance | undefined) {
    formEl && formEl.resetFields()
    emits('update:modelValue', false)
}

async function init(val: any) {
    await nextTick()
    if (val?.id) {
        title.value = '编辑'
        state.value = cloneDeep(val)
        state.value.region = val?.region ? val.region.split(',') : []
    }
    else {
        title.value = '新增'
        state.value = cloneDeep(initialState)
    }
}

watch(data, (val: any) => {
    if (val)
        init(val)
}, {
    deep: true,
    immediate: true,
})
</script>

<template>
    <ElDialog v-model="modelValue"
              width="800"
              :close-on-click-modal="false"
              :title="title"
              class="h-700 overflow-scroll"
              @close="close"
    >
        <ElForm ref="formRef"
                :model="state"
                :rules="rules"
                label-width="auto"
                label-position="top"
        >
            <ElFormItem label="专题名称"
                        prop="name"
            >
                <ElInput v-model="state.name" />
            </ElFormItem>

            <ElFormItem label="专题分类"
                        prop="catId"
            >
                <ElSelect v-model="state.catId">
                    <ElOption v-for="item in videoType"
                              :key="item.id"
                              :value="item.id"
                              :label="item.name"
                    />
                </ElSelect>
            </ElFormItem>

            <ElFormItem label="辖区"
                        prop="region"
            >
                <ElSelect v-model="state.region"
                          multiple
                >
                    <ElOption v-for="item in area"
                              :key="item.id"
                              :value="item.name"
                              :label="item.name"
                    />
                </ElSelect>
            </ElFormItem>

            <ElRow>
                <ElCol :span="12">
                    <ElFormItem label="封面图"
                                prop="img"
                    >
                        <UpdatedOss v-model="state.img"
                                    accept=".png,.jpg,.jpeg"
                        />
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElFormItem label="专题内容"
                        prop="info"
            >
                <Editor v-model="state.info"
                        :is-jc-mall="false"
                        :height="300"
                />
            </ElFormItem>

            <ElFormItem label="排序号"
                        prop="sortOrder"
            >
                <ElInputNumber v-model="state.sortOrder"
                               :precision="0"
                               :step="1"
                />
            </ElFormItem>

            <div style="text-align: center;">
                <ElButton type="primary"
                          @click="doSave(formRef)"
                >
                    确定
                </ElButton>

                <ElButton @click="close(formRef)">
                    取消
                </ElButton>
            </div>
        </ElForm>
    </ElDialog>
</template>
